﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.Productionorders;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Productionorders;

namespace Reporting.API.Application.CommandHandler.Productionorders
{
    /// <summary>
    /// 添加生产工单
    /// </summary>
    public class AddProductionorderCommandHandler : IRequestHandler<AddProductionorderCommand, ApiResult>
    {

        private readonly IProductionorderRepository  _productionorderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductionorderCommandHandler> _logger;

        public AddProductionorderCommandHandler(ILogger<AddProductionorderCommandHandler> logger, IMapper mapper, IProductionorderRepository productionorderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionorderRepository = productionorderRepository;
        }


        public async Task<ApiResult> Handle(AddProductionorderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 将 DTO 映射为实体类
                var userEntity = _mapper.Map<Productionorder>(request);

                // 调用仓储层添加用户
                var addProductionorder = await _productionorderRepository.InsertAsync(userEntity);

                // 返回成功结果  StatusCodeEnum
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加失败");
                throw;
            }
        }
    }
}
